﻿using System;
using System.Windows.Forms;
using Framework;
using Koala.Framework;
using Koala.JiraTool.Login.Models;

namespace Koala.JiraTool.Login.Controls
{
    public partial class LoginControl : UserControl, IDependency
    {
        private readonly ILoginController _loginController;

        private readonly INotificationController _notificationController;
        private readonly IDataPersistence _dataPersistence;

        public LoginControl(ILoginController loginController, INotificationController notificationController, IDataPersistence dataPersistence)
        {
            _loginController = loginController;
            _notificationController = notificationController;
            _dataPersistence = dataPersistence;
            InitializeComponent();
        }

        #region Event

        private void LoginControl_Load(object sender, EventArgs e)
        {
            var model = _dataPersistence.Get<UserInfo>();
            if (model == null)
                return;
            txtUserName.Text = model.UserName;
            txtPassword.Text = model.Password;
            Login();
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            Login();
            var model = new UserInfo { UserName = txtUserName.Text, Password = txtPassword.Text };
            _dataPersistence.Save(model);
        }

        private void btnLogout_Click(object sender, EventArgs e)
        {
            btnLogout.Enabled = btnLogin.Enabled = true;
            _notificationController.Message(_loginController.Logout() ? "注销成功。" : "注销失败，但你仍然可以使用其他账号进行登录。");
        }

        private void LoginControl_Enter(object sender, EventArgs e)
        {
            if (_loginController.IsLogin())
            {
                _notificationController.Message("登录成功欢迎：{0}。", _loginController.GetUserName());
                btnLogin.Enabled = false;
                btnLogout.Enabled = true;
            }
            else
            {
                btnLogin.Enabled = true;
                btnLogout.Enabled = false;
            }
        }

        #endregion Event

        #region Private Method

        private void Login()
        {
            string message;
            if (_loginController.Login(txtUserName.Text, txtPassword.Text, out message))
            {
                _notificationController.Message("登录成功欢迎：{0}。", _loginController.GetUserName());
                btnLogin.Enabled = false;
                btnLogout.Enabled = true;
            }
            else
            {
                _notificationController.Message(message);
                btnLogin.Enabled = true;
                btnLogout.Enabled = false;
            }
        }

        #endregion Private Method
    }
}